package MagneticCave;


import MagneticCave.Node;

public class Minimax 
{
	private Node theTree;
	private int maxDepth;
	
	private final int INFINITY = 10000;
	
	public Minimax(int maxDepth, Node theTree)
	{
		this.theTree = theTree;
		this.maxDepth = maxDepth;
	}
	
	public int getNextMove()
	{
		getMax(theTree, maxDepth);
		
		// find the child of theTree whose value matches that of theTree
		Node nextNode = null;
		for (Node child : theTree.getChildren())
		{
			if (theTree.hasEqualValue(child))
			{
				if (nextNode != null)
				{
					if (nextNode.getDepthFromHere() > child.getDepthFromHere())
						nextNode = child;
				}
				else
					nextNode = child;
			}
		}
		
		// nextNode should not be null
		return nextNode.getValue();
	}
	
	private int getMax(Node node, int depth)
	{
		if (depth <= 0)
		{
			node.setValue(heuristic(node));
			return node.getValue();
		}
		node.setValue(-INFINITY*2);
		
		boolean depthIncreased = false;
		
		for (Node child : node.getChildren())
		{
			if (!depthIncreased)
			{
				depthIncreased = true;
				node.increaseDepth();
			}
			node.setValue(Math.max(node.getValue(), getMin(child, depth - 1)));
		}
		return node.getValue();
	}
	
	
	private int getMin(Node node, int depth)
	{
		if (depth <= 0)
		{
			node.setValue(heuristic(node));
			return node.getValue();
		}
		node.setValue(INFINITY*2);
		
		boolean depthIncreased = false;
		
		for (Node child : node.getChildren())
		{
			if (!depthIncreased)
			{
				depthIncreased = true;
				node.increaseDepth();
			}
			node.setValue(Math.min(node.getValue(), getMax(child, depth - 1)));
		}
		return node.getValue();
	}
	
	private int heuristic(Node node)
	{
		return node.getValue();
	}
}
